import { Table, Card, Form, Row, Col, Button, Space } from 'antd';
import { useState } from 'react';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';

interface ProTableProps {
  columns: any[];
  searchFields?: any[];
  fetchData: (params: any) => Promise<{ items: any[]; total: number }>;
}

export function ProTable({ columns, searchFields, fetchData }: ProTableProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const handleSearch = async (values: any) => {
    setLoading(true);
    try {
      const result = await fetchData({
        ...values,
        page: pagination.current,
        limit: pagination.pageSize,
      });
      setData(result.items);
      setPagination(prev => ({ ...prev, total: result.total }));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card>
      {searchFields && (
        <Form form={form} onFinish={handleSearch} className="mb-4">
          <Row gutter={16}>
            {searchFields.map(field => (
              <Col span={6} key={field.name}>
                <Form.Item name={field.name} label={field.label}>
                  {field.component}
                </Form.Item>
              </Col>
            ))}
            <Col span={6}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button 
                  icon={<ReloadOutlined />}
                  onClick={() => form.resetFields()}
                >
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      )}
      <Table
        columns={columns}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={(newPagination) => setPagination(newPagination)}
      />
    </Card>
  );
}